function linesIntersection(x1,y1,x2,y2,x3,y3,x4,y4){
	if(!(x1!=null&&x2!=null&&y1!=null&&
		y2!=null&&x3!=null&&x4!=null&&
		y3!=null&&y4!=null)){
		return null;
	}
	var answer=[2];
	var a1=y1-y2;
	var b1=x2-x1;
	var c1=x1*y2-x2*y1;
	var a2=y3-y4;
	var b2=x4-x3;
	var c2=x3*y4-x4*y3;
	var s=a1*b2-a2*b1
	if(!(s)){
		return null;
	}
	answer[0]=(c2*b1-c1*b2)/s;
	answer[1]=(c1*a2-c2*a1)/s;
	return answer;
}

function segmentsIntersection(x1,y1,x2,y2,x3,y3,x4,y4){
	var answer=linesIntersection(x1,y1,x2,y2,x3,y3,x4,y4);
	if(answer==null){
		return null;
	}
	var s;
	if(x1>x2){
		s=x1;
		x1=x2;
		x2=s;
	}
	if(x3>x4){
		s=x3;
		x3=x4;
		x4=s;
	}
	if(y1>y2){
		s=y1;
		y1=y2;
		y2=s;
	}
	if(y3>y4){
		s=y3;
		y3=y4;
		y4=s;
	}
	var dx=0.01;
	x1-=dx;
	x2+=dx;
	y1-=dx;
	y2+=dx;
	x3-=dx;
	x4+=dx;
	y3-=dx;
	y4+=dx;
	if((answer[0]<=x2&&answer[0]<=x4&&answer[0]>=x1&&answer[0]>=x3)&&
		(answer[1]<=y2&&answer[1]<=y4&&answer[1]>=y1&&answer[1]>=y3)){
		return answer;
	}else{
		return null;
	}
}
function distance(x,y,x0,y0,x1,y1)
{
    var v0 = x1 - x0;
    var v1 = y1 - y0;
    var w0 = x - x0;
    var w1 = y - y0;
	var c1 = w0*v0 + w1*v1;
    if (c1 <= 0 )
        return Math.sqrt((x-x0)*(x-x0)+(y-y0)*(y-y0));
	var c2 = v0*v0 + v1*v1;
    if (c2 <= c1 )
        return Math.sqrt((x-x1)*(x-x1)+(y-y1)*(y-y1));
    var b = c1 / c2 ;
    var pb0 =x0 + b*v0;
    var pb1 =y0 + b*v1;
    return Math.sqrt((x-pb0)*(x-pb0)+(y-pb1)*(y-pb1));
}